const { Modal, Form, Input, Button, Col, Row, Tabs, Space } = antd;
const { Search } = Input;
const { TabPane } = Tabs;

const CoderEd = ({ visible, onCancel, onOk }) => {
  const [form] = Form.useForm();

  const [inputLoading, setInputLoading] = useState(false);
  const [loading, setLoading] = useState(false);
  const [loadingDetail, setLoadingDetail] = useState(false);

  const [idea, setIdea] = useState({});
  const [outline, setOutline] = useState('');

  const [prompts, setPrompts] = useState([]);
  const [value, setValue] = React.useState('');

  const [editingPrompt, setEditingPrompt] = useState(null);
  const [editingPromptVars, setEditingPromptVars] = useState([]);
  const [editingPromptOpts, setEditingPromptOpts] = useState([]);

  const [formVisible, setFormVisible] = useState(false);

  const [agent, setAgent] = useState(false);
  
  useEffect(() => {
    loadPrompts();
  }, []);

  const loadPrompts = async () => {
    const allPrompts = await db.prompts.toArray();
    setPrompts(allPrompts);
  };

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  const DelPrompt = async () => {
    prn('del prompt',  editingPrompt)

    await db.prompts.delete(editingPrompt.id);
    loadPrompts();
  }

  const cid = 'editor_coder_gen'
  const getEd = () => {
    let editor = window[cid]
    return editor
  }

  const setEdVal = (val) => {
    let editor = getEd()
    if (editor){
      editor.setValue(val)
    }
  }

  const getEdVal = () => {
    let editor = getEd()
    if (editor){
      return editor.getValue()
    }else{
      return ''
    }
  }

  const handleRowClick = (prompt) => {    
    setEdVal(prompt.content)
    setEditingPrompt(prompt)

    if ( prompt.vars ) {
      let vars = prompt.vars.map(it=>{
        it.label = it.name
        return it
      })

      let opts = prompt.opts ? prompt.opts.options : {} 
      setEditingPromptVars(vars)
      setEditingPromptOpts(opts)
    }else{
      setEditingPromptVars([])
      setEditingPromptOpts([])
    }
  };


  const updateDoc = ()=>{}


  const streamLLM = async (value) => {
      prn('streamLLM', value)

      let llm = $.streamGlmApi
      // llm = $.streamSiliconflowAPI
      // llm = $.streamQwQAPI
      await llm(value, (ret)=>{
        setEdVal(getEdVal(cid) + ret)
      })    
  }

  const callLLM = async () => {
    let tpl = getEdVal()

    setLoading(true);

    setEdVal('')

    // let llm = $.streamGlmApi
    // await llm(tpl, (ret)=>{
    //   setEdVal(getEdVal(cid) + ret)
    // })

    await streamLLM(tpl)

    setLoading(false);
    
  }

  const onTplOk = (tpl_ret) =>{
    prn('tpl_ret', tpl_ret)

    setEdVal(tpl_ret)
  }

  const handleKeyDown = async (e) => {
    if (e.key === 'Enter') {
      setInputLoading(true)
      setEdVal('')
      
      // let ret = await $.callSiliconflowAPI(value)
      // prn('SFlow ret', ret)

      // let llm = $.streamGlmApi
      // llm = $.streamSiliconflowAPI
      // await llm(value, (ret)=>{
      //   setEdVal(getEdVal(cid) + ret)
      // })

      await streamLLM(value)

      setInputLoading(false)
    }
  };

  const savePrompt = async ()=>{
    let content = getEdVal()
    prn('savePrompt', editingPrompt, content)

    let newData = editingPrompt
    newData.content = getEdVal()
    await db.prompts.update(editingPrompt.id, newData);
    loadPrompts()
  }

  const copyContent = async ()=>{
    $.copyToClipboard(getEdVal())
  }


  const genNovel = async ()=>{
    $.generateNovel((content, agent)=>{
      // prn(agent)

      window.agent = agent
      
      setAgent(agent)
      setEdVal(content)
    })
  }

  const genNovelNext = async ()=>{
    $.generateNovelNext(agent, (content)=>{
      setEdVal(content)
    })
  }

  const handleOptSubmit = async (data) =>{
    prn('data', data)

    editingPrompt.opts = data
    await db.prompts.update(editingPrompt.id, editingPrompt);
  }

  return (
    <Modal
      title="代码生成"
      width={1700}
      height={1000}
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
      footer={[
        <Space size="large">
          <Button onClick={genNovel} >gen novel</Button>
          <Button onClick={genNovelNext} >gen-next novel</Button>
          <Button onClick={copyContent} >复制</Button>
          <Button onClick={savePrompt} >保存</Button>
          <Button onClick={callLLM} loading={loading}>生成</Button>
        </Space>
      ]}      
    >

    
    <Row>
      <Col span={8}>

      
    <Tabs defaultActiveKey="1">
      <TabPane tab="prompts" key="1">
        <SelectPrompt prompts={prompts} onRowClick={handleRowClick} prompt_tag={'小说作家'}
          editingPrompt={editingPrompt}
          vars ={editingPromptVars}
          opts = {editingPromptOpts}        
         />

        <Button type="primary" danger onClick={DelPrompt} style={{margin: '10px'}}> DelPrompt </Button>

        <ProptOption 
          onTplOk={onTplOk}
          prompt={editingPrompt}
          vars ={editingPromptVars}
          opts = {editingPromptOpts}
        />



      </TabPane>
      <TabPane tab="options" key="2">
        <ProptOption 
          onTplOk={onTplOk}
          prompt={editingPrompt}
          vars ={editingPromptVars}
          opts = {editingPromptOpts}
        />
      </TabPane>
      <TabPane tab="novel" key="3">
        <NovelPanel />
      </TabPane>
    </Tabs>

      </Col>
      <Col span={16}>
         <MonacoEditor 
          container_id='coder_gen'
          init_doc={''}
          updateDoc={updateDoc}
         />
        <Search value={value} onChange={handleChange} onKeyDown={handleKeyDown} loading={inputLoading} size="large"maxLength={50} />
      </Col>
    </Row>    

    </Modal>
  );
};

